<template>
  <div>
    <page-dialog
      v-show="finishInfo.visible"
      :title="finishInfo.title"
      v-model:visible="finishInfo.visible"
      :width="finishInfo.width"
      :bt-loading="finishInfo.btLoading"
      :bt-list="finishInfo.btList"
      @reset="reset"
    >
      <!-- 配件使用 -->
      <div class="model-panel">
        <div class="model-panel-title">
          <p>配件使用</p>
        </div>
        <NewPageFilter
          v-model:query="mountingsUseInfo.filterInfo.query"
          :filter-btn="mountingsUseInfo.filterInfo.list"
          :isFromDialog="true"
        >
          <template v-slot:filter-removeMountings>
            <el-button
              :disabled="!mountingsUseInfo.tableInfo.selections.length"
              @click="removeMountings(undefined)"
              icon="Delete"
              >删除</el-button
            >
          </template>
        </NewPageFilter>
        <el-form
          :model="mountingsUseInfo.tableInfo"
          ref="tableForm"
          style="width: 100%"
        >
          <!-- 表格 -->
          <dialog-table
            ref="mountingsUseTable"
            :refresh="mountingsUseInfo.tableInfo.refresh"
            :init-curpage="mountingsUseInfo.tableInfo.initCurpage"
            v-model:data="mountingsUseInfo.tableInfo.data"
            :api="mountingsUseInfo.tableInfo.api"
            :query="mountingsUseInfo.tableInfo.query"
            :pager="false"
            :tabIndex="true"
            :field-list="mountingsUseInfo.tableInfo.fieldList"
            :handle="mountingsUseInfo.tableInfo.handle"
            :row-class-name="mountingsUseInfo.tableRowClassName"
            @handleEvent="selectMountingsTable"
          >
            <template v-slot:col-price="scope">
              <el-form-item
                :prop="`data.${scope.$index}.price`"
                :rules="
                  scope.$index >= 0
                    ? [
                        {
                          validator: $validate.positiveMoneyNoZeroAsset,
                          trigger: ['blur', 'change'],
                        },
                        {
                          required: scope.$index >= 0,
                          message: '请输入单价',
                          trigger: 'blur',
                        },
                      ]
                    : []
                "
              >
                <el-input-number
                  style="width: 100%; margintop: 18px"
                  v-model.lazy="scope.row.price"
                  clearable
                  controls-position="right"
                  :precision="
                    $store.state.permission.systemConfig.assets_price_precision
                  "
                  @change="changePrice($event, scope.row, `price`)"
                  :min="0"
                  :max="999999999999999"
                />
              </el-form-item>
            </template>
            <template v-slot:col-qty="scope">
              <el-form-item
                :prop="`data.${scope.$index}.qty`"
                :rules="
                  scope.$index >= 0
                    ? [
                        {
                          validator: $validate.positiveNoAsset,
                          trigger: ['blur', 'change'],
                        },
                        {
                          required: scope.$index >= 0,
                          message: '请输入数量',
                          trigger: 'blur',
                        },
                      ]
                    : []
                "
              >
                <el-input-number
                  style="width: 100%; margintop: 18px"
                  v-model.lazy="scope.row.qty"
                  clearable
                  controls-position="right"
                  :precision="2"
                  @change="changePrice($event, scope.row, `qty`)"
                  @input="changePrice($event, scope.row, `qty`)"
                  :min="0"
                  :max="999999999999999"
                />
              </el-form-item>
            </template>
            <template v-slot:col-replaceTime="scope">
              <el-form-item
                :prop="`data.${scope.$index}.replaceTime`"
                :rules="
                  scope.$index >= 0
                    ? [
                        {
                          validator: validateUseTime,
                          trigger: 'blur',
                        },
                        {
                          required: scope.$index >= 0,
                          message: '请选择更换日期',
                          trigger: 'change',
                        },
                      ]
                    : []
                "
              >
                <el-date-picker
                  v-model="scope.row.replaceTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择日期"
                ></el-date-picker>
              </el-form-item>
            </template>
          </dialog-table>
        </el-form>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>养护执行</p>
        </div>
        <el-form
          :model="handleMaintenanceInfo.tableInfo"
          style="width: 100%"
        >
          <!-- 表格 -->
          <dialog-table
            ref="mountingsUseTable"
            :refresh="handleMaintenanceInfo.tableInfo.refresh"
            :init-curpage="handleMaintenanceInfo.tableInfo.initCurpage"
            v-model:data="handleMaintenanceInfo.tableInfo.data"
            :api="handleMaintenanceInfo.tableInfo.api"
            :query="handleMaintenanceInfo.tableInfo.query"
            :pager="false"
            :tabIndex="true"
            :check-box="false"
            :field-list="handleMaintenanceInfo.tableInfo.fieldList"
            :row-class-name="handleMaintenanceInfo.tableRowClassName"
            @handleEvent="handleEventItems"
          >
            <template v-slot:col-result="scope">
              <radio-model
                v-model="scope.row.result"
                typeCode="appearance_quality"
                class="form-input"
              />
            </template>
            <template v-slot:col-remark="scope">
              <el-form-item
                class="form-input"
                :prop="`data.${scope.$index}.remark`"
              >
                <el-input v-model="scope.row.remark"> </el-input>
              </el-form-item>
            </template>
          </dialog-table>
        </el-form>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>完工</p>
        </div>
      </div>

      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="finishInfo.formInfo.ref"
        :data="finishInfo.formInfo.data"
        :field-list="finishInfo.formInfo.fieldList"
        :rules="finishInfo.formInfo.rules"
        :label-width="finishInfo.formInfo.labelWidth"
      >
        <template v-slot:form-maintenancePrincipalValue>
          <el-input
            type="input"
            :disabled="true"
            :class="row.id ? '' : 'not-mongolia'"
            placeholder="请选择养护负责人"
            v-model="finishInfo.formInfo.data.maintenancePrincipalValue"
          >
            <template #append>
              <el-icon v-if="!id" @click="openUserWindow"
                ><MoreFilled
              /></el-icon>
            </template>
            <!-- <i
              @click="openUserWindow"
              slot="append"
              :class="
                row.id
                  ? 'el-icon-more i_more i-more-disabled'
                  : 'el-icon-more i_more i-more'
              "
            ></i> -->
          </el-input>
        </template>
        <template v-slot:form-filePathList>
          <UploadImg
            v-if="finishInfo.formInfo.data.complete == 1"
            v-model:value="finishInfo.formInfo.data.filePathList"
            :action="action"
            :title="'附件'"
            :fileType="['png', 'jpg', 'jpeg']"
            :response-fn="handleResponse"
          />
          <span v-else>-</span>
        </template>
      </page-form>
    </page-dialog>
    <!-- 选择配件 -->
    <SelectAccessories
      v-if="accessoriesInfo.visible"
      v-model:show-dialog="accessoriesInfo.visible"
      :query="accessoriesInfo.query"
      :tableKey="accessoriesInfo.tableKey"
      @callback="changeAccessories"
    />

    <!-- 养护负责人 -->
    <SelectUsers
      v-if="selectUserInfo.visible"
      v-model:showDialog="selectUserInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :query="selectUserInfo.query"
      :check-box="false"
      :highlight-row="true"
      @callback="selectUserCallback"
    />
  </div>
</template>
<script setup name="finsish">
import PageDialog from '@/components/PageDialog/index'
import PageForm from '@/components/PageForm/index'
import {
  clearDeviceMaintenanceTaskAccessories,
  getDeviceMaintenanceTaskAccessoriesCustomizeListPage,
  saveDeviceMaintenanceTaskAccessoriesList,
  getDeviceMaintenanceTaskProgramAll,
  updateBatchListDeviceMaintenanceTaskProgram,

  completeDeviceMaintenanceTask,
  getDeviceMaintenanceTaskById,
} from '@/api/repair.js'
import moment from 'moment'
import { getCustomizeSetting } from "@/api/customize";
import SelectAccessories from "@/components/SelectAccessories/index";
import SelectUsers from "@/components/SelectUsers/index";
import RadioModel from '@/components/ModelRadio'
import { getRrgUserList } from "@/api/base.js";
import UploadVideo from "@/components/UploadVideo/index";
import axios from "axios";

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'row'])

let validateCompleteTime = (rule, value, callback) => {
  let currentTime = moment(new Date()).format('YYYY-MM-DD')
  console.log(value, currentTime, value > currentTime)
  if (value > currentTime) {
    callback(new Error('完工时间不能大于当前时间！'))
  } else {
    callback()
  }
}

const filePathList = ref([])
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const selectUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {
    orgId: '',
  },
})
//选择配件
const accessoriesInfo = reactive({
  visible: false,
  tableKey:
    "accessoriesArchivesDialog-com.slip.spd.entity.vo.asset.settings.AccessoriesArchivesVO",
  query: {
    id: {
      queryType: "NOT_IN",
      queryCategory: "AND",
      value: "",
    },
  },
});
//配件使用相关
const mountingsUseInfo = reactive({
  orderId: "",
  visible: false,
  title: "配件使用",
  btLoading: false,
  type: "",
  msg: "",
  width: "75%",
  flag: true,
  // 过滤相关配置
  filterInfo: {
    query: {
      customizeUserVO: {},
      queryMap: {},
    },
    list: [
      {
        label: "添加",
        type: "button",
        event: addMountings,
        show: true,
      },
      {
        label: "删除",
        type: "slot",
        value: "removeMountings",
      },
    ],
  },
  // 表格相关
  tableInfo: {
    refresh: 1,
    initCurpage: 1,
    data: [],
    selections: [],
    api: null,
    query: {
      customizeUserVO: {},
      queryMap: {
        orderId: {
          queryType: "EQUALS",
          queryCategory: "AND",
          columnName: "`order_id`",
          queryResource: 0,
          value: props.row.id,
        },
      },
    },
    // query: {
    //   // orderType: 53,
    //   orderId: "",
    //   sort: "create_time desc",
    // },
    fieldList: [],
    handle: {
      fixed: "right",
      label: "操作",
      width: "50",
      btList: [
        {
          label: "删除",
          event: removeMountings,
          popconfirmText: "删除后将改变数据,是否继续？",
          show: true,
        },
      ],
    },
  },
});
//配件使用相关
const handleMaintenanceInfo = reactive({
  orderId: "",
  visible: false,
  title: "养护执行",
  btLoading: false,
  type: "",
  msg: "",
  width: "75%",
  flag: true,
  btList: [
    {
      label: "关闭",
      event: handleCloseHandleMaintenance,
      show: true,
    },
    {
      label: "保存",
      type: "primary",
      event: saveHandleMaintenance,
      show: true,
    },
  ],
  // 过滤相关配置
  filterInfo: {
    query: {
      customizeUserVO: {},
      queryMap: {},
    },
    list: [
      { label: "添加项目", type: "button", event: addItem },
      { type: "slot", value: "removeItem" },
    ],
  },
  // 表格相关
  tableInfo: {
    refresh: 1,
    initCurpage: 1,
    api: getDeviceMaintenanceTaskProgramAll,
    query: {
      orderId: props.row.id,
    },
    data: [],
    selections: [],
    fieldList: [
      {
        label: "养护部位",
        value: "maintenanceParts",
        // type: "slot",
      },
      {
        label: "养护内容与要求",
        value: "contentRequire",
        // type: "slot",
      },
      {
        label: "养护结果",
        value: "result",
        type: "slot",
      },
      {
        label: "备注",
        value: "remark",
        type: "slot",
      },
    ],
  },
});
//完工相关
const finishInfo = reactive({
  visible: false,
  title: '执行',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseFinish, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveFinish,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {
      filePathList: [],
    },
    fieldList: [
      {
        label: "是否完工",
        value: "complete",
        type: "radio-model",
        code: "default_yes_or_no",
      },
      {
        label: '养护状态',
        value: 'status',
        type: 'select-model',
        code: 'device_maintenance_kind',
        require: true,
        disabled: true,
      },
      {
        label: '养护负责人',
        value: 'maintenancePrincipalValue',
        type: 'slot',
        require: true,
        disabled: true,
      },
      {
        label: '完工时间',
        value: 'completeDate',
        type: 'date',
        required: true,
        // disabled: true,
      },

      {
        label: '合计工时(h)',
        value: 'totalHours',
        type: 'number',
        // precision: 1,
        required: true,
        // disabled: true,
      },
      {
        label: '养护服务费',
        value: 'maintenanceAmount',
        type: 'number',
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
      },
      {
        label: '养护材料费',
        value: 'maintenanceMaterialsAmount',
        type: 'number',
        disabled: true,
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
      },
      {
        label: '费用合计',
        value: 'amount',
        type: 'number',
        disabled: true,
        max: 999999999999999,
        formatter: proxy.$fn.TripartiteMethodAsset,
        precision:
          proxy.$store.state.permission.systemConfig.assets_price_precision,
      },
      {
        label: '完工说明',
        value: 'completeRemark',
        type: 'textarea',

        // disabled: true,
      },
      {
        label: '完工图片',
        value: 'filePathList',
        type: 'slot',
        className: 'not-br',
      },
    ],
    rules: {
      completeDate: [
        { required: true, message: '请选择完工时间', trigger: 'change' },
        {
          validator: validateCompleteTime,
          trigger: 'change',
        },
      ],
      // totalHours: [
        // { required: true, message: '请输入合计工时', trigger: 'change' },
      // ],
      // completeRemark: [
        // { required: true, message: '请输入完工说明', trigger: 'blur' },
      // ],
    },

    labelWidth: '120px',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => props.visible,
  (newVal) => {
    finishInfo.visible = newVal
    selectUserInfo.visible = false
    accessoriesInfo.visible = false;
  },
  {
    immediate: true,
  }
)
watch(
  () => props.row,
  (newVal) => {
    finishInfo.formInfo.data.id = newVal.id
    mountingsUseInfo.tableInfo.query.queryMap.orderId.value = newVal.id;
    handleMaintenanceInfo.tableInfo.query.orderId = newVal.id;

  },
  {
    immediate: true,
  }
)
watch(
  () => finishInfo.formInfo.data.complete,
  (val) => {
    console.log(val)
    finishInfo.formInfo.fieldList.map(item => {
      if(['completeDate', 'totalHours', 'maintenanceAmount', 'completeRemark'].includes(item.value)) {
        item.disabled = !Boolean(Number(val))
      }
    })
  },
  {
    deep: true,
  }
);

watch(
  () => finishInfo.formInfo.data,
  (val) => {
    let maintenanceAmount = val.maintenanceAmount || 0
    let maintenanceMaterialsAmount = val.maintenanceMaterialsAmount || 0
    val.amount = proxy.$fn.accAdd(maintenanceAmount, maintenanceMaterialsAmount)
  },
  {
    deep: true,
  }
)

watch(
  () => mountingsUseInfo.tableInfo.data,
  (val) => {
    finishInfo.formInfo.data.maintenanceMaterialsAmount = 0
    if (val.length) {
      let ids = [];
      val.forEach((row) => {
        ids.push(row.productId);
        if(row.sumAmount) {
          finishInfo.formInfo.data.maintenanceMaterialsAmount = finishInfo.formInfo.data.maintenanceMaterialsAmount + row.sumAmount
        }
      });
      accessoriesInfo.query.id.value = String(ids);
      if (proxy.$refs.mountingsUseTable) {
        proxy.$refs.mountingsUseTable.setListInfoTotal(val.length);
      }
    } else {
      accessoriesInfo.query.id.value = "";
      if (proxy.$refs.mountingsUseTable) {
        proxy.$refs.mountingsUseTable.setListInfoTotal(0);
      }
    }
  },
  {
    deep: true,
  }
);


onMounted(() => {
  getFormData()
  setTimeout(() => {
    getItemsList();
  }, 100);

})
let obj = {
  price: {
    label: "单价",
    value: "price",
    componentType: "price",
    type: "slot",
    formatter: proxy.$fn.TripartiteMethodAsset,
    show: false,
    hidden: true,
  },
  qty: {
    label: "数量",
    value: "qty",
    type: "slot",
    componentType: "number",
    formatter: proxy.$fn.TripartiteMethodAsset,
    show: false,
    hidden: true,
  },
  preUnitValue: {
    label: "计量单位",
    value: "preUnitValue",
    componentType: "input",
    type: "column",
    show: false,
    hidden: true,
  },
  replaceTime: {
    label: "更换日期",
    value: "replaceTime",
    componentType: "input",
    show: false,
    type: "slot",
    hidden: true,
  },
  sumAmount: {
    label: "金额",
    value: "sumAmount",
    componentType: "price",
    type: "column",
    formatter: proxy.$fn.TripartiteMethodAsset,
    show: false,
    hidden: true,
  },
};
mountingsUseInfo.tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
});
getCustomize();
function getCustomize() {
  let tableInfo = mountingsUseInfo.tableInfo;
  let param = {
    tableKey:
      "deviceMaintenanceTaskAccessoriesList-com.slip.spd.entity.domain.device.maintenance.task.DeviceMaintenanceTaskAccessories",
  };
  tableInfo.isSysGroup = false;
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      );
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.isSysGroup = true;
        }
      }
      mountingsUseInfo.tableInfo.query.customizeUserVO = data;
      tableInfo.api = getDeviceMaintenanceTaskAccessoriesCustomizeListPage;
      getMountingsUseList();
    }
  });
}
function addMountings() {
  accessoriesInfo.visible = true;
}
function getMountingsUseList() {
  mountingsUseInfo.tableInfo.refresh = Math.random();
}
//删除配件
function removeMountings(row = undefined) {
  if (row) {
    mountingsUseInfo.tableInfo.data = mountingsUseInfo.tableInfo.data.filter(
      (item) => item.productId !== row.productId
    );
  } else {
    mountingsUseInfo.tableInfo.data = mountingsUseInfo.tableInfo.data.filter(
      (row) => {
        return !mountingsUseInfo.tableInfo.selections.includes(row);
      }
    );
  }
}
function changePrice(e, row, str) {
  if (str === "qty") {
    row.sumAmount = proxy.$fn.accMul(e, row.price);
  } else if (str === "price") {
    row.sumAmount = proxy.$fn.accMul(e, row.qty);
  }
  console.log(e, row, str, "e, row,data");
}
function validateUseTime(rule, value, callback) {
  let currentTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
  if (value > currentTime) {
    callback(new Error("更换日期不能大于当前时间！"));
  } else {
    callback();
  }
}
function getFormData() {
  getDeviceMaintenanceTaskById(props.row.id).then((resp) => {
    if (resp && resp.success) {
      finishInfo.formInfo.data = resp.data
      if(!resp.data.completeDate) {
        finishInfo.formInfo.data.completeDate = moment(new Date()).format("YYYY-MM-DD")
      }
      finishInfo.formInfo.data.complete = Number(resp.data.complete)

    }
  })
}
function reset() {
  emit('callbackFinish', false)
}
//完工保存
//完工保存
async function saveFinish() {
  let valid1 = await proxy.$refs["tableForm"].validate((valid) => valid)
  console.log(valid1)
  finishInfo.formInfo.ref.validate((valid) => {
    if (valid && valid1) {
      // deviceMaintenanceTaskAccessoriesVOList 配件
      let deviceMaintenanceTaskAccessoriesVOList = []
      let data = mountingsUseInfo.tableInfo.data
      if (data.length) {
        data.forEach((item) => {
          deviceMaintenanceTaskAccessoriesVOList.push({
            productId: item.productId,
            calcQty: item.qty,
            qty: item.qty,
            orderId: props.row.id,
            price: item.price,
            sumAmount: item.sumAmount,
            replaceTime: item.replaceTime,
          });
        });
      }
      // deviceMaintenanceTaskProgramVOList  项目
      let params = {
        ...finishInfo.formInfo.data,
        deviceMaintenanceTaskAccessoriesVOList: deviceMaintenanceTaskAccessoriesVOList,
        deviceMaintenanceTaskProgramVOList: handleMaintenanceInfo.tableInfo.data,
        complete: Boolean(Number(finishInfo.formInfo.data.complete))
      }
      completeDeviceMaintenanceTask(params).then((resp) => {
        if (resp && resp.success) {
          emit("callbackFinish", false);
        }
        // finishInfo.visible = false;
      });
    }
  });
}
function handleCloseFinish() {
  // finishInfo.visible = false;
  emit('callbackFinish', false)
}
function handleResponse(response, file) {
  return file
}
//养护负责人
function openUserWindow() {
  selectUserInfo.visible = true
}
function selectUserCallback(row) {
  if (row) {
    finishInfo.formInfo.data['maintenancePrincipalValue'] = row.name
    finishInfo.formInfo.data['maintenancePrincipal'] = row.id
  } else {
    finishInfo.formInfo.data['maintenancePrincipalValue'] = ''
    finishInfo.formInfo.data['maintenancePrincipal'] = ''
  }
}

//选择配件
function changeAccessories(data) {
  console.log(data, "-------------------选择配件");
  if (data.length) {
    data.forEach((item) => {
      let obj = {
        productId: item.id,
        preCommonName: item.commonName,
        preStandard: item.standard,
        preUnitValue: item.unitName,
        price: item.referencePrice,
        ...item,
      };
      mountingsUseInfo.tableInfo.data.push(obj);
    });
    accessoriesInfo.visible = false;
  }
}
function selectMountingsTable(event, data) {
  switch (event) {
    case "tableCheck":
      mountingsUseInfo.tableInfo.selections = [...data];
      break;
  }
}

function handleEventItems(event, data) {
  switch (event) {
    case "tableCheck":
      handleMaintenanceInfo.tableInfo.selections = data;
      break;
  }
}
function handleCloseHandleMaintenance() {
  emit("callbackHandleMaintenance", false);
}
function getItemsList() {
  handleMaintenanceInfo.tableInfo.refresh = Math.random();
}
function saveHandleMaintenance() {
  updateBatchListDeviceMaintenanceTaskProgram(
    handleMaintenanceInfo.tableInfo.data
  ).then((resp) => {
    if (resp && resp.success) {
      emit("callbackHandleMaintenance", false);
    }
  });
}
function addItem() {}
</script>
<style>
.i-more-disabled {
  cursor: not-allowed;
}
.i-more {
  background-color: #ffffff;
  cursor: pointer;
  height: 26px;
}
</style>
